<template>
  <page-wrap>
    <div class="mb-10px">
      <a-button type="primary" @click="addAction()">新增</a-button>
      <a-button class="ml-2" @click="expand">{{
        expanded ? '展开' : '收起'
      }}</a-button>
    </div>
    <table-wrap
      :columns="tableColumns"
      :data="dataList"
      :pagination="false"
      default-expand-all-rows
      row-key="id"
      node-key="id"
      :loading="loading"
      @register="tableRegister"
    >
      <template #icon="{ record }">
        <component :is="record.icon" v-if="record.icon" />
      </template>
    </table-wrap>
  </page-wrap>

  <modal-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :fullscreen="false"
    width="500"
    content-height="600"
  >
    <ClientWebModuleForm
      ref="formRef"
      :data="dataModel"
      :tree-list="dataList"
      :current-parent-id="currentParentId"
      :depth="currentDepth"
    />
    <template #footer>
      <a-button type="primary" :loading="submitLoading" @click="submit()">
        保存
      </a-button>
      <a-button @click="dialogVisible = false">关闭</a-button>
    </template>
  </modal-dialog>
</template>
<script setup lang="tsx">
  import { Link } from '@arco-design/web-vue';

  import {
    listAllTreeApi,
    getApi,
    saveApi,
    updateApi,
    removeApi,
  } from '@/api/tenant/client-web-module';
  import { ClientWebModuleVO } from '@/api/tenant/client-web-module/types';
  import { useTable } from '@/hooks/table';

  import ClientWebModuleForm from './components/client-web-module-form.vue';

  const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
      return await listAllTreeApi();
    },
    fetchDelApi: async () => {
      return await removeApi(currentId.value as string);
    },
  });
  const { dataList, loading } = tableState;
  const { getList, delList, expandAll } = tableMethods;

  const tableColumns = reactive<TableColumn[]>([
    {
      field: 'index',
      title: '序号',
      type: 'index',
    },
    {
      field: 'name',
      title: '名称',
      width: 200,
    },
    {
      field: 'title',
      title: '标题',
    },
    {
      field: 'type',
      title: '类型',
      width: 100,
      type: 'enumTag',
      enumName: 'ModuleType',
    },
    {
      field: 'icon',
      title: '图标',
      slotName: 'icon',
    },
    {
      field: 'path',
      title: '访问路径',
    },
    {
      field: 'component',
      title: '组件',
      width: 400,
      render: (data: any) => {
        const component = data.record.component;
        return (
          <>
            {component === '#'
              ? '顶级目录'
              : component === '##'
              ? '子目录'
              : component}
          </>
        );
      },
    },
    {
      field: 'permissionCode',
      title: '授权编码',
    },
    {
      field: 'hidden',
      title: '显示/隐藏',
      type: 'enumTag',
      enumName: 'Hidden',
    },
    {
      field: 'action',
      title: '操作',
      width: 150,
      render: (data: any) => {
        const row = data.record;
        return (
          <>
            {row.type < 3 && (
              <Link onClick={() => addAction(row.id, row.depth)}>新增</Link>
            )}
            <Link onClick={() => editAction(row.id)}>编辑</Link>
            <Link onClick={() => delAction(row.id)}>删除</Link>
          </>
        );
      },
    },
  ]);

  const expanded = ref(false);
  const dataModel = ref<any>();

  const currentId = ref<string>();
  const currentParentId = ref<string>();
  const currentDepth = ref(0);

  const formRef = ref<ComponentRef<typeof ClientWebModuleForm>>();

  const actionType = ref('');
  const dialogTitle = ref('');
  const dialogVisible = ref(false);
  const submitLoading = ref(false);

  // 新增菜单
  const addAction = (id?: string, depth?: number) => {
    dataModel.value = undefined;
    currentParentId.value = id;
    currentDepth.value = depth ?? 0;
    actionType.value = 'add';
    dialogTitle.value = '新增';
    dialogVisible.value = true;
  };

  // 编辑菜单
  const editAction = async (id: string) => {
    dataModel.value = await getApi(id);
    actionType.value = 'edit';
    dialogTitle.value = '编辑';
    dialogVisible.value = true;
  };

  const submit = async () => {
    const formData = await formRef.value?.submit();
    if (formData) {
      submitLoading.value = true;
      try {
        let res;
        if (actionType.value == 'add') {
          res = await saveApi(formData as ClientWebModuleVO);
        } else {
          res = await updateApi(formData as ClientWebModuleVO);
        }
        if (res) {
          getList();
          MessageInfo.success('操作成功');
          dialogVisible.value = false;
        }
      } catch (error) {
        console.log(error);
      } finally {
        submitLoading.value = false;
      }
    }
  };

  // 删除菜单
  const delAction = async (id: string) => {
    currentId.value = id;
    await delList(1);
  };

  const expand = async () => {
    await expandAll(expanded.value);
    expanded.value = !expanded.value;
  };
</script>
